import path from 'node:path';
import { __path } from '@e/methods/path';
import { ImageInfo } from '@p/main-windowObject';
import { generateLocalReferenceURL } from '@e/methods/url';
import {
	matchMarkdownAllImageReferencesRegex,
	isInlineImageReferenceRegExp,
	matchInlineImageReferencePathRegExp,
	matchTagImageReferencePathRegExp,
	isUrlRegExp,
	isRelativePathRegExp,
	matchbase64DateURLRegex,
} from '@e/utils/regexp';

// 匹配问号及后面所有字符
const reg = /\?.*$/;

export function getImageInfo(content: string, dirPath: string) {
	// 匹配出所有图片引用
	let pathArr = content.match(matchMarkdownAllImageReferencesRegex);

	if (!pathArr) return [];

	return pathArr.reduce((t, item, i) => {
		type Temp = Pick<ImageInfo, 'absolute' | 'localReference' | 'existById' | 'filename' | 'fileExist'>;
		const temp: Temp = {};
		let target: ImageInfo['target'];
		let type: ImageInfo['type'];
		let referenceType: ImageInfo['referenceType'];
		let exist: ImageInfo['exist'] = false;

		// 获取图片引用的图片路径
		if (isInlineImageReferenceRegExp.test(item)) {
			const matchs = item.match(matchInlineImageReferencePathRegExp) as string[];
			target = matchs[1];
			referenceType = 'inline';
		} else {
			const matchs = item.match(matchTagImageReferencePathRegExp) as string[];
			target = matchs[1];
			referenceType = 'img';
		}

		// 获取图片路径的类型
		if (isUrlRegExp.test(target)) {
			type = 'url';
		} else if (path.isAbsolute(target)) {
			type = 'absolute';

			temp.absolute = target.replace(reg, '');
			temp.localReference = generateLocalReferenceURL(temp.absolute);
			temp.filename = path.basename(temp.absolute);
			temp.fileExist = __path.check.exist(temp.absolute);
		} else if (matchbase64DateURLRegex.test(target)) {
			type = 'base64URL';
		} else if (isRelativePathRegExp.test(target)) {
			type = 'relative';

			temp.absolute = path.join(dirPath, target.replace(reg, ''));
			temp.localReference = generateLocalReferenceURL(temp.absolute);
			temp.filename = path.basename(temp.absolute);
			temp.fileExist = __path.check.exist(temp.absolute);
		} else {
			type = 'unknown';
		}

		// 判断path是否重复
		let index = t.findIndex((i) => i.target === target);
		if (index !== -1) {
			exist = true;
			temp.existById = t[index].id;
		}

		t.push({
			id: i,
			target,
			type,
			initial: item,
			referenceType,
			exist,
			...temp,
		});

		return t;
	}, [] as ImageInfo[]);
}
